﻿using NFine.Code;
using NFine.Data;
using NFine.Domain.Entity.Biz;
using NFine.Domain._02_ViewModel;
using NFine.Domain._04_IRepository.Biz;
using NFine.Domain.Entity.ProductManage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NFine.Domain.IRepository.ProductManage;
using NFine.Repository.ProductManage;
using NFine.Domain.Entity.SystemManage;
using NFine.Domain._03_Entity.Biz;
using NFine.Repository.SystemManage;
using NFine.Domain.IRepository.SystemManage;

namespace NFine.Repository.Biz
{
    public class UserOrderRepository : RepositoryBase<UserOrderEntity>, IUserOrderRepository
    {
        private IProductRepository productRepository = new ProductRepository();
        private IUserPropertyRepository userPropertyRepository = new UserPropertyRepository();
        private IMemberBonusRepository memberbonusRepository = new MemberBonusRepository();
        private IUserRepository userRepository = new UserRepository();


        public int updateOrderStatus(string Id, int orderStatus)
        {
            int result = 0;
            if (orderStatus >= 0)
            {
                string time = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                result = dbcontext.Database.ExecuteSqlCommand(string.Format("update biz_user_order set F_OrderStatus={0}, F_BackTime='{1}' where F_Id='{2}'", orderStatus, time, Id));
            }
            else
            {
                UserOrderEntity entity = FindEntity(Id);
                if (entity != null)
                {
                    if (entity.F_IsUseIntegral)
                    {
                        var userP = userPropertyRepository.FindEntity(t => t.F_UserId == entity.F_MemberId);
                        if (userP != null)
                        {
                            userP.F_Property += entity.F_ProductPrice;
                            userP.F_LastModifyTime = DateTime.Now;

                            entity.F_OrderStatus = orderStatus;
                            entity.F_BackTime = DateTime.Now;

                            MemberBonusEntity mbEntity = new MemberBonusEntity();
                            mbEntity.F_MemberId = userP.F_UserId;
                            mbEntity.F_OrderId = entity.F_Id;
                            mbEntity.F_BonusType = 10;//10代表订单退费
                            mbEntity.F_BonusTime = DateTime.Now;
                            mbEntity.F_BonusAmount = entity.F_ProductPrice;
                            mbEntity.F_Id = Common.GuId();
                            mbEntity.F_bz = "订单退费，订单额：" + entity.F_TotalMoney + "元，实际消费积分：" + entity.F_ProductPrice;

                            using (var db = new RepositoryBase().BeginTrans())
                            {
                                db.Update<UserPropertyEntity>(userP);
                                db.Update(entity);
                                db.Insert<MemberBonusEntity>(mbEntity);
                                result = db.Commit();
                            }
                        }
                    }
                    else
                    {
                        entity.F_OrderStatus = orderStatus;
                        entity.F_BackTime = DateTime.Now;
                        result = this.Update(entity);
                    }
                }
            }

            return result;
        }

        public int UpdateBackMoneyStatus(string id, int backMoneyStatus)
        {
            return dbcontext.Database.ExecuteSqlCommand(string.Format("update biz_user_order set F_BackMoneyStatus={0} where F_Id='{1}'", backMoneyStatus, id));
        }
        public int UpdateBalanceByMonth(DateTime date)
        {
            string sql =
                string.Format(
                    "UPDATE biz_user_order SET F_IsBalance = 1 WHERE F_OrderStatus = 2 AND DATE_FORMAT(F_OrderTime, '%Y%m') = DATE_FORMAT('{0}' , '%Y%m');",
                    date);
            return dbcontext.Database.ExecuteSqlCommand(sql);
        }

        public int CurMonthOrderCount()
        {
            return GetSingleToInt(string.Format("select COUNT(*) as result FROM  biz_user_order WHERE F_OrderStatus>0 and DATE_FORMAT(F_OrderTime, '%Y%m') = DATE_FORMAT(CURDATE( ) , '%Y%m')"));
        }

        public decimal? CurMonthMoneyCount()
        {
            return GetSingleToDecimal("select SUM(F_TotalMoney) as result FROM  biz_user_order WHERE F_OrderStatus>0 and DATE_FORMAT(F_OrderTime, '%Y%m') = DATE_FORMAT(CURDATE( ) , '%Y%m')");
        }

        public decimal? AllMoneyCount()
        {
            return GetSingleToDecimal("select SUM(F_TotalMoney) as result FROM  biz_user_order where F_OrderStatus = 3 ");
        }

        /// <summary>
        /// 获取数据最大时间
        /// </summary>
        /// <returns></returns>
        public DateTime getMaxTime()
        {
            return GetSingleToDateTime("SELECT MAX(F_OrderTime) FROM biz_user_order WHERE F_OrderStatus = 2 AND F_SendGoodsStatus = 1");
        }

        /// <summary>
        /// 获取数据最小时间
        /// </summary>
        /// <returns></returns>
        public DateTime getMinTime()
        {
            return GetSingleToDateTime("SELECT MIN(F_OrderTime) FROM biz_user_order WHERE F_OrderStatus = 2 AND F_SendGoodsStatus = 1");
        }

        /// <summary>
        /// 年消费总额
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        public decimal getSumMoneyByYear(string year)
        {
            if (!string.IsNullOrEmpty(year) && year != "-1")
                return GetSingleToDecimal(string.Format("SELECT SUM(F_TotalMoney) FROM biz_user_order WHERE OrderStatus >0  AND DATE_FORMAT( OrderTime, '%Y' ) = '{0}'", year));
            else
                return GetSingleToDecimal("SELECT SUM(F_TotalMoney) FROM biz_user_order WHERE F_OrderStatus >0");
        }

        public decimal SumUserConsumeByMonth(string userId, DateTime date)
        {
            string sql = string.Format("SELECT SUM(F_TotalMoney) FROM biz_user_order " +
                                       "WHERE F_MemberId = '{0}' AND F_OrderStatus >0 " +
                                       "AND DATE_FORMAT(F_OrderTime, '%Y%m') = DATE_FORMAT('{1}' , '%Y%m') " +
                                       "AND F_IsBalance = 0"
                                       , userId, date);
            return GetSingleToDecimal(sql);
        }

        public decimal SumAllOrderByMonth(DateTime date)
        {
            string sql = string.Format("SELECT SUM(F_TotalMoney) FROM biz_user_order " +
                                       "WHERE  F_OrderStatus >0 " +
                                       "AND DATE_FORMAT(F_OrderTime, '%Y%m') = DATE_FORMAT('{0}' , '%Y%m') " +
                                       "AND F_IsBalance = 0"
                , date);
            return GetSingleToDecimal(sql);
        }

        /// <summary>
        /// 今日消费总额
        /// </summary>
        /// <returns></returns>
        public decimal getSumMoneyByNow()
        {
            return GetSingleToDecimal("SELECT SUM(F_TotalMoney) FROM biz_user_order WHERE F_OrderStatus>0 AND TO_DAYS(F_OrderTime) = TO_DAYS(NOW())");
        }
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="parentOrder"></param>
        /// <param name="list_OrderItems"></param>
        /// <returns></returns>
        public int SubmitOrder(UserOrderEntity parentOrder, List<OrderItemEntity> list_OrderItems, OrderActionEntity actionEntity)
        {

            try
            {
                MemberBonusEntity mb = null;
                if (parentOrder.F_IsUseIntegral)
                {
                    UserDetailEntity ude = new UserDetailEntity();
                    ude.F_UserId = parentOrder.F_MemberId;
                    var curMoney = memberbonusRepository.GetMemberCurAmount(parentOrder.F_MemberId);

                    if (curMoney < parentOrder.F_TotalMoney)
                    {
                        return 0;
                    }
                    UserEntity user = userRepository.FindEntity(parentOrder.F_MemberId);
                    mb = new MemberBonusEntity();
                    mb.F_Id = Common.GuId();
                    mb.F_MemberId = parentOrder.F_MemberId;
                    mb.F_OrderId = parentOrder.F_Id;
                    mb.F_BonusAmount = parentOrder.F_TotalMoney * -1;
                    mb.F_BonusLevel = 5;//也不知道这个是干啥的
                    mb.F_BonusTime = DateTime.Now;
                    mb.F_BonusType = 3;//余额支付
                    mb.F_CurAmount = curMoney + mb.F_BonusAmount;
                    mb.F_bz = string.Format("会员[{0}({1})]的余额支付", user.F_RealName, user.F_Account);
                }
                //开启事务
                using (var db = new RepositoryBase().BeginTrans())
                {
                    //  如果是积分抵扣的,直接更新用户资产表
                    if (mb != null)
                        db.Insert(mb);

                    db.Insert(parentOrder);


                    db.Insert<OrderItemEntity>(list_OrderItems);

                   // db.Insert<OrderActionEntity>(actionEntity);

                    return db.Commit();
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        /// <summary>
        /// 检查三个小时后还未支付的订单，自动作废
        /// </summary>
        /// <param name="id"></param>
        /// <param name="backMoneyStatus"></param>
        /// <returns></returns>
        public int orderZF_Auto()
        {
            return dbcontext.Database.ExecuteSqlCommand(string.Format("UPDATE biz_user_order SET F_OrderStatus=-2 WHERE DATE_SUB(NOW(), INTERVAL 3 HOUR)>F_OrderTime AND F_OrderStatus=0"));
        }
        /// <summary>
        /// 检查十天前的用户未完成的订单，自动完成
        /// </summary>
        /// <returns></returns>
        public int orderWC_Auto() {
            return dbcontext.Database.ExecuteSqlCommand(string.Format("UPDATE biz_user_order SET F_OrderStatus=3 WHERE DATE_SUB(NOW(), INTERVAL 10 DAY)>F_OrderTime AND F_OrderStatus=2"));
        }
    }
}
